package com.nomi.blog.utils;

import java.security.MessageDigest;

public class Md5Utils {
    // 盐值，增加密码复杂度
    private static final String SALT = "nomi";

    // 对密码进行加密
    public static String encrypt(String password) {
        try {
            // 创建MessageDigest示例并指定算法
            MessageDigest md = MessageDigest.getInstance("MD5");

            //添加盐值
            String passwordWithSalt = password + SALT;

            //计算哈希值
            byte[] hash = md.digest(passwordWithSalt.getBytes());

            //转换为16进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : hash) {
                // 按位与,把字节转换为无符号的整数
                String hex = Integer.toHexString(b & 0xff);
                if (hex.length() == 1) {
                    sb.append("0");
                }
                sb.append(hex);
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }
}
